import { Form, Modal, Input, InputNumber, Tree, Select } from 'antd';
import { useEffect, useState } from 'react';

import commonService from '@/api/services/commonService';

export function RoleModal({ title, show, formValue, onOk, onCancel }: any) {
  const [form] = Form.useForm();
  const [menus, setMenus] = useState([]);
  const [checked, setChecked] = useState([]);
  const [checkedNodes, setCheckedNodes] = useState([]);

  useEffect(() => {
    commonService.getCateListApi('menu', {}).then((res) => {
      setMenus(res);
    });
  }, []);

  interface MenuNode {
    id: number;
    children?: MenuNode[];
  }
  
  /**
   * 回填时过滤未全选的父节点ID
   * @param checkedIds 后端返回的选中ID数组（如[1,8,9]）
   * @param treeData 完整的树结构数据
   * @returns 过滤后的ID数组（确保父节点只有全选时才会被保留）
   */
  const filterParentIds = (checkedIds: number[], treeData: MenuNode[]): number[] => {
    const checkedSet = new Set(checkedIds);
    const parentMap = new Map<number, boolean>();
  
    // 检查每个父节点是否所有子节点都被选中
    const checkParents = (nodes: MenuNode[]) => {
      nodes.forEach(node => {
        if (node.children && node.children.length > 0) {
          const allChildrenChecked = node.children.every(child => checkedSet.has(child.id));
          parentMap.set(node.id, allChildrenChecked);
          checkParents(node.children);
        }
      });
    };
  
    checkParents(treeData);
  
    // 过滤结果：保留叶子节点 + 全选的父节点
    return checkedIds.filter(id => {
      const isParent = parentMap.has(id);
      return !isParent || (isParent && parentMap.get(id));
    });
  };
  
  useEffect(() => {
    if (formValue.id) {
      commonService.getMenuIdsApi('menu', { roleId: formValue.id }).then((res) => {
        const list:any =  res.split(',').map((item: any) => {
          return Number(item);
        });
        const filteredIds:any = filterParentIds(list, menus);
        setChecked(filteredIds
        );
      });
    }
    form.setFieldsValue({ ...formValue });
  }, [formValue, form]);

  const onCheck = (res: any, e:any) => {
    setCheckedNodes(e.checkedNodes);
    setChecked(res);
  };

  const handleOk = () => {
    if (formValue.id) {
      const list: any = [];
      checkedNodes.forEach((item: any) => {
        if(!list.includes(item.id)) {
          list.push(item.id);
        }
        if(!list.includes(item.parentId)) {
          list.push(item.parentId);
        }
      });
      commonService.setPermApi('RoleMenu', { roleId: formValue.id, menuId: list });
    }
    onOk({ ...formValue, ...form.getFieldsValue() });
  };

  return (
    <Modal title={title} open={show} onOk={() => handleOk()} onCancel={onCancel}>
      <Form
        initialValues={formValue}
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        layout="horizontal"
      >
        <Form.Item<any> label="角色名称" name="roleName" required>
          <Input />
        </Form.Item>

        <Form.Item<any> label="角色权限" name="roleKey" required>
          <Input />
        </Form.Item>

        <Form.Item<any> label="显示顺序" name="roleSort">
          <InputNumber style={{ width: '100%' }} />
        </Form.Item>

        <Form.Item<any> label="角色状态" name="status" required>
          <Select
            options={[
              { label: '可用', value: '0' },
              { label: '禁用', value: '1' },
            ]}
          />
        </Form.Item>

        <Form.Item<any> label="备注" name="remark">
          <Input.TextArea />
        </Form.Item>

        {formValue.id ? (
          <Form.Item<any> label="权限" name="dataScope">
            <Tree
              checkable
              multiple
              checkedKeys={checked}
              treeData={menus}
              onCheck={onCheck}
              fieldNames={{
                key: 'id',
                children: 'children',
                title: 'menuName',
              }}
            />
          </Form.Item>
        ) : (
          ''
        )}
      </Form>
    </Modal>
  );
}
